#include "checkout.h"
#include "ui_checkout.h"

checkOutWidget::checkOutWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::checkOutWidget)
{
    ui->setupUi(this);
    connect(this->ui->pushButton,&QPushButton::clicked,this,&QWidget::close);
}

checkOutWidget::~checkOutWidget()
{
    delete ui;
}

void checkOutWidget::fillFrame(const QString &roomNo, const time_t sessionId, const double cost)
{
    QSqlQuery query(database::getInstance()->getDB());
    query.exec(QString("SELECT * FROM records WHERE sessionId=%1;").arg(QString().setNum(sessionId)));
    this->ui->label_2->setText(roomNo);
    this->ui->label_4->setText(QString().setNum(sessionId));
    this->ui->label_7->setText(QString().setNum(cost));
    QTreeWidgetItem *root=ui->treeWidget->invisibleRootItem();
    QString fileName;
    fileName.append("detail_Sid:").append(QString().setNum(sessionId)).append("Roomid:").append(roomNo).append(".txt");
    QString path;
    path.append("/tmp/detail/").append(fileName);
    std::ofstream fout(path.toStdString());
    fout<<"Detail Records:"<<std::endl;
    fout<<"roomNo:"<<roomNo.toStdString()<<"\t\t\t"<<"sessionId:"<<sessionId<<std::endl;
    fout<<"----------------------------------------------------------------------------"<<std::endl;
    fout<<"Time\t\t\tOperation\tTemperature\tfanSpeed\tCost"<<std::endl;
    fout<<"----------------------------------------------------------------------------"<<std::endl;
    while (query.next()){
        QTreeWidgetItem *item=new QTreeWidgetItem(root);
        time_t i=query.value(1).toLongLong();
        QString date=QString::fromLatin1(ctime(&i));
        date.chop(6);
        item->setText(0,date);
        double temp=query.value(3).toDouble();
        item->setText(1,QString().setNum(temp));
        int wind=query.value(4).toInt();
        item->setText(2,QString().setNum(wind));
        int isOpen=query.value(5).toInt();
        item->setText(3,isOpen==1?QString("Yes"):QString("No"));
        int isServed=query.value(6).toInt();
        item->setText(4,isServed==1?QString("Yes"):QString("No"));

        QString oper=query.value(7).toString();
        item->setText(5,oper);
        int cost=query.value(8).toInt();
        fout<<(date.toStdString())<<"\t"<<(oper.toStdString())<<"\t\t"<<temp<<"\t\t"<<wind<<"\t"<<cost<<std::endl;
    }
    fout<<std::endl<<"Bill:"<<std::endl;
    fout<<"Total fee:"<<cost<<std::endl;
    fout.close();
}
